require(['jquery',
         'global',
         'module/util',
         'bootbox.min',
         'module/datatables',
         'permission',
         'bootstrap-datetimepicker.zh-CN',
         'bootstrap-datetimepicker',
         'module/ajax',
         'jquery-weui',
         'bootstrap',
         'pixeladmin'], 
function($, global, util, bootbox, datatables ,permission){
	window.PixelAdmin.start();
	
	var workType = $("#workType").val();
	
	var _isbnTable = null, _dictConfig = ["ISBN_ORDER_STATUS", "ISBN_INFORMATION_STATUS", "ISBN_TREATMENT_OPINION"];
	var selectConfig = function() {
		doLoadSelect('treatmentOpinion', 'ISBN_TREATMENT_OPINION', '', '全部处理意见');
		doLoadSelect('orderStatus', 'ISBN_ORDER_STATUS', '', '全部购书状态');
	}
	
	// 查询
	var doSearch = function() {
		_isbnTable.setParams(util.getSearchData('#search-area'));
		_isbnTable.invoke("fnDraw");
	};

	// 查询table的回调函数列表
	var isbnTableFunction = {
		barcode : function(data,type,full) {
			var html = '<input type="checkbox" class="element hide" id="checkall" value="'+full.id+'"/>&nbsp;&nbsp;';
			html    += '<a href="'+global.context + '/web/isbnmanage/view?barcode='+full.barcode+'" target="_blank">'+full.barcode+'</a>';
			return html;
		},
		orderStatus : function(data,type,full) {
			return global.dict['ISBN_ORDER_STATUS'][full.orderStatus];
		},
		infomationStatus : function(data,type,full) {
			return global.dict['ISBN_INFORMATION_STATUS'][full.infomationStatus];
		},
		operate : function(data,type,full) {
			var html = '<a href="'+global.context + '/web/isbnmanage/editor?barcode='+full.barcode;
			if(full.isbnInformationId != null){
				html += '&isbnInformationId='+full.isbnInformationId;
			}
			html += '" target="_blank"><span class="glyphicon glyphicon-edit"></span>&nbsp;编辑</a>&nbsp;&nbsp;&nbsp;';
			if("buy" == workType){
				var nowDay = util.getNumberDate();
				var url_taobao = "https://s.taobao.com/search?q="+full.barcode+"&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.50862.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_"+nowDay;
				html += '<a href="'+ url_taobao + '" target="_blank" ><span class="glyphicon glyphicon-shopping-cart"></span>&nbsp;淘宝</a>&nbsp;&nbsp;&nbsp;';
				
			}
			
			if(!$.isEmptyObject(workType) && full.isbnInformationId && 3 == full.orderStatus){
				if("buy" == workType && permission.isbn_buy){
					if("0" == full.infomationStatus){
						//可执行操作 【可填充信息填充完成】
						html += '<a style="cursor:pointer;" class="domethod" data-method="informationFillCando" data-isbninformationid="'+full.isbnInformationId+'"><span class="glyphicon glyphicon-cog"></span>&nbsp;提交已填充信息</a>&nbsp;&nbsp;&nbsp;';
					}
				}else if("complete" == workType && permission.isbn_complete){
					if("1" == full.infomationStatus){
						//可执行操作 【已完善信息】
						html += '<a style="cursor:pointer;" class="domethod" data-method="informationFillComplete" data-isbninformationid="'+full.isbnInformationId+'"><span class="glyphicon glyphicon-cog"></span>&nbsp;已完善信息</a>&nbsp;&nbsp;&nbsp;';
					}else if("2" == full.infomationStatus){
						//可执行操作 【图片已上传】
						html += '<a style="cursor:pointer;" class="domethod" data-method="pageFillComplete" data-isbninformationid="'+full.isbnInformationId+'"><span class="glyphicon glyphicon-cog"></span>&nbsp;图片已上传</a>&nbsp;&nbsp;&nbsp;';
					}
				}else if("publish" == workType && permission.isbn_publish){
					if("3" == full.infomationStatus){
						//可执行操作 【已审核】
						html += '<a style="cursor:pointer;" class="domethod" data-method="judgeComplete" data-isbninformationid="'+full.isbnInformationId+'"><span class="glyphicon glyphicon-cog"></span>&nbsp;已审核</a>&nbsp;&nbsp;&nbsp;';
						//可执行操作 【废弃】
						html += '<a style="cursor:pointer;" class="domethod" data-method="drop" data-isbninformationid="'+full.isbnInformationId+'"><span class="glyphicon glyphicon-remove"></span>&nbsp;废弃</a>&nbsp;&nbsp;&nbsp;';
					}else if("4" == full.infomationStatus){
						//可执行操作 【已发布】
						html += '<a style="cursor:pointer;" class="domethod" data-method="publish" data-isbninformationid="'+full.isbnInformationId+'"><span class="glyphicon glyphicon-cog"></span>&nbsp;发布</a>&nbsp;&nbsp;&nbsp;';
					}else if("5" == full.infomationStatus){
						//可执行操作 【取消发布】
						html += '<a style="cursor:pointer;" class="domethod" data-method="unpublish" data-isbninformationid="'+full.isbnInformationId+'"><span class="glyphicon glyphicon-cog"></span>&nbsp;取消发布</a>&nbsp;&nbsp;&nbsp;';
					}
				}
			}
			return html;
		}
	};
	
	//表格查询后回调函数
	var tableCallBack = function(res) {
		$(".barcode").each(function() {
			$(this).click(function() {
				
				
				return false;
			});
		});
		$(".glyphicon-trash").each(function() {
			var row = $(this).parent().parent();
			$(this).click(function() {
				$.confirm({
				  title: '确认删除？',
				  text: '你确定需要删除该记录，如需要找回请联系技术？',
				  onOK: function () {
				     deleteIsbn(this.barcode, function() {
					  	 $(row).hide(1000);
				    	 setTimeout(function(){
				    		 $(row).remove();
				    	 }, 1000);
				     });
				  },
				  onCancel: function () {
				  }
				});
				return false;
			});
		});
	};
	
	// isbn 软删除
	var deleteIsbn = function(barcode, callback) {
		$.ajax({
	        url : global.context + '/web/isbndealt/deleteByBarcode',
	        data : {barcode : barcode},
            type : 'POST',
            dataType : 'json',
	        success : function(result) {
	        	if(callback) callback();
	        },
	        error : function(e) {
	        	$.alert("删除失败");
	        }
		});
	}
	
	// 初始化表格
	var initTable = function(){
		$('#isbnTable').css('width', "100%");
		var options = {};
		options.tableId = '#isbnTable';
		options.sAjaxSource = global.context + "/web/isbndealt/searchIsbnDealtByCon";
        options.functionList = isbnTableFunction;
        options.iDisplayLength = 10;
        options.callBack = tableCallBack;
        _isbnTable = datatables.init(options);
        _isbnTable.setParams(util.getSearchData("#search-area"));
		return _isbnTable.create();
	};

	var doLoadSelect = function(id, dictName, firstValue, nameDesc) {
		util.selectPadding({
			id : id,
			data : global.dict[dictName],
			firstValue : firstValue,
			firstName : nameDesc
		});
	}
	
	// 初始化时间输入框
	var initDateInput = function() {
		$('#startTime').datetimepicker({
	        language:  'zh-CN',
	        format: 'yyyy-mm-dd hh:ii:ss',
	        weekStart: 1,
	        todayBtn:  1,
			autoclose: 1,
			todayHighlight: 1,
			startView: 2,
			forceParse: 0,
	        showMeridian: 1
	    });
	    $('#endTime').datetimepicker({
	        language:  'zh-CN',
	        format: 'yyyy-mm-dd hh:ii:ss',
	        weekStart: 1,
	        todayBtn:  1,
			autoclose: 1,
			todayHighlight: 1,
			startView: 2,
			forceParse: 0,
	        showMeridian: 1
	    });		
	    util.bindDompareData("startTime", "endTime");// 时间比较
	}
	
	var initDoMethod = function(){
        //isbn业务处理      
        $("body").on('click','.domethod',function(){
            var target = $(this);
            var method = target.data('method');
            var isbninformationid = target.data('isbninformationid');
            var data = {
                isbnInformationId:isbninformationid
            }
            $.confirm({
                  title: '确认操作',
                  text: '你确定要这么处理吗？',
                  onOK: function () {
                      $.ajax({
                            type: "POST",
                             url: global.context +"/web/business/"+method,
                             data: util.stringify_aoData(data),
                             contentType: 'application/json; charset=UTF-8',
                             dataType:"json",
                             async: false,  
                            'success' : function(data) {
                            _isbnTable.invoke("fnDraw");
                            },
                            'error' : function() {
                            }
                        });
                  },
                  onCancel: function () {}
            });
        });
    }
	
	//获取当前时间 yyyyMMdd
	function getNowFormatDate() {
	    var date = new Date();
	    var year = date.getFullYear();
	    var month = date.getMonth() + 1;
	    var strDate = date.getDate();
	    if (month >= 1 && month <= 9) {
	        month = "0" + month;
	    }
	    if (strDate >= 0 && strDate <= 9) {
	        strDate = "0" + strDate;
	    }
	    var currentdate = year  + month  + strDate;
	    return currentdate;
	}
	
	var bindEvent = function() {
		$("#search-btn").click(doSearch);// 搜索按钮点击事件
		
		initDateInput();
		
		util.initTableCheckbox("checkall");
		
		initDoMethod();
	}
	
	// init start
	var init  = function() {
		initTable();//初始化table
		
		global.doInitDictData({
			data : _dictConfig,
			success : function() {
				selectConfig();
				doSearch();
			}
		});
		
		bindEvent();
	};
	// init end
	
	
	init();
});